﻿using Com.Lancetinc.Evs.Helpers;
using System;
using System.Diagnostics;
using System.IO;
using System.Timers;
using System.Windows.Media.Animation;

namespace Com.Lancetinc.Evs
{
    /// <summary>
    ///     开屏显示
    /// </summary>
    public partial class SplashScreenWin
    {
        private static SplashScreenWin _instance;

        public SplashScreenWin()
        {
            InitializeComponent();
            this.Title = AppConsts.AppTitle;
            this.Loaded += SplashScreenWin_Loaded;
            this.Closed += SplashScreenWin_Closed;
            _instance = this;
        }

        public static void CloseWin()
        {
            _instance?.CloseWindow();
            _instance = null;
        }

        private void SplashScreenWin_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            var levsDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "levs");
            DirUtil.EnsureDirectoryExists(levsDir);
            var launchFile = Path.Combine(levsDir, "launch.txt");
            File.WriteAllText(launchFile, DateTime.Now.Ticks.ToString());
        }

        /// <inheritdoc />
        protected override void OnContentRendered(EventArgs e)
        {
            base.OnContentRendered(e);

            // 确保启动程序已经结束
            TryKillLauncher();
        }

        private void SplashScreenWin_Closed(object sender, System.EventArgs e)
        {

        }

        private void CloseWindow()
        {
            var sb = (Storyboard)FindResource("SbHideWindow");
            sb.Completed += (s, e) =>
            {
                this.Close();
            };
            sb.Begin();
        }

        private void TryKillLauncher()
        {
            var timer = new Timer(1000);
            timer.AutoReset = false;
            timer.Elapsed += (s, e) =>
            {
                var ps = Process.GetProcessesByName(AppConsts.LauncherProcessName);
                if (ps.Length == 0)
                    return;
                try
                {
                    ps[0].Kill();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                }
            };
            timer.Start();
        }
    }
}